﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using CE.Configuration;
using CE.Global;
using CE.User;
using CE.Image;
using CE.CarInsurance;
using CE.Mail;
using CE.Company;
using CE.Database;
using CE.CMI;

public partial class cmi_cmi_detail : MyLanguageBasePage
{
    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Session[General.ProviderCompanyId] = 45;
        //Session[General.CMICarId] = 78789;
        //Session[General.CMIId] = 2;
        //string _url = CE.Global.General.GetUrl("~/car-insurance/proposalforms/cmi_form.aspx", Page);
        //Response.Redirect(_url);

        Master.Page.Title = Resources.Title.CompulsuryInsurance;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.CMIKeyword;
        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.CMIDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        if (!IsPostBack)
        {
            LoadManufactYearList();
            ClearAllList();
            SetCTPLStartDate();
            RegistrationDate();
            //ExpiryMonth();
            //GetInsurance();
            if (System.Globalization.CultureInfo.CurrentCulture.Name == "th-TH")
            {
                GetProvinceTH();
                GetCarColorTH();
            }
            else
            {
                GetProvinceEN();
                GetCarColorEN();
            }

            if (Session[General.UserId] != null)
            {
                ShowCustomerDetail(Convert.ToInt64(Session[General.UserId]));
                lbnLoginPopup.Visible = false;
            }

            if (Session["CMITYPE"] != null)
            {
                hidCMIType.Value = Session["CMITYPE"].ToString();
                if (Session["CMICARTYPE"] != null)
                {
                    SetupDetail();

                    // Tax only
                    if (Session["CMITYPE"].ToString() == "3")
                    {
                        divCMIDetail.Style.Add("display", "none");
                        chkTax.Checked = true;
                        rfvChassisNo.Enabled = false;
                        rfvColor.Enabled = false;
                        rfvEngineSize.Enabled = false;
                        rfvCTPLStartDay.Enabled = false;
                        rfvCTPLStartMonth.Enabled = false;
                    }
                    else if (Session["CMITYPE"].ToString() == "2")
                    {
                        chkTax.Checked = true;
                    }
                }
                else
                {
                    if (Session[General.CMIId] != null)
                    {
                        FillIn();
                    }
                    else
                    {
                        Response.Redirect("cmi-select.aspx");
                    }
                }
            }
            else
            {
                if (Session[General.CMIId] != null)
                {
                    FillIn();
                }
                else
                {
                    Response.Redirect("cmi-select.aspx");
                }
            }
        }
        else
        {
            lblMessage.Text = "";
        }
    }

    #region Setup

    private void SetupDetail()
    {
        lblCMITitle.Text = Session["CMITITLE"].ToString();
        if (Session["CMICTPL"] != null) lblSumCTPL.Text = Session["CMICTPL"].ToString();
        if (Session["CMICTPLDISC"] != null) lblSumDiscount.Text = Session["CMICTPLDISC"].ToString();
        if (Session["CMITOTAL"] != null) lblTotal.Text = Session["CMITOTAL"].ToString();
        if (Session["CMITOTAL"] != null) hidTotal.Value = Session["CMITOTAL"].ToString();
        hidCarType.Value = Session["CMICARTYPE"].ToString();

        if (hidCarType.Value != "1")
        {
            SetupCarWeight();
            divCarWeight.Style.Add("display", "");
        }
    }

    private void SetupCarWeight()
    {
        ddlCarWeight.Items.Clear();
        if (hidCarType.Value == "2")
        {
            //Pick-Up 2 Doors
            ddlCarWeight.Items.Add(new ListItem("< 500", "300"));
            ddlCarWeight.Items.Add(new ListItem("501 - 750", "450"));
            ddlCarWeight.Items.Add(new ListItem("751 - 1,000", "600"));
            ddlCarWeight.Items.Add(new ListItem("1,001 - 1,250", "750"));
            ddlCarWeight.Items.Add(new ListItem("1,251 - 1,500", "900"));
            ddlCarWeight.Items.Add(new ListItem("1,501 - 1,750", "1050"));
            ddlCarWeight.Items.Add(new ListItem("1,751 - 2,000", "1350"));
            ddlCarWeight.Items.Add(new ListItem("2,001 - 2,500", "1650"));
            ddlCarWeight.Items.Add(new ListItem("2,501 - 3,000", "1950"));
            ddlCarWeight.Items.Add(new ListItem("3,001 - 3,500", "2250"));
            ddlCarWeight.Items.Add(new ListItem("3,501 - 4,000", "2550"));
            ddlCarWeight.Items.Add(new ListItem("4,001 - 4,500", "2850"));
            ddlCarWeight.Items.Add(new ListItem("4,501 - 5,000", "3150"));
            ddlCarWeight.Items.Add(new ListItem("5,001 - 6,000", "3450"));
            ddlCarWeight.Items.Add(new ListItem("6,001 - 7,000", "3750"));
            ddlCarWeight.Items.Add(new ListItem("> 7000", "4050"));
        }
        else if (hidCarType.Value == "3")
        {
            //Van
            ddlCarWeight.Items.Add(new ListItem("< 500", "150"));
            ddlCarWeight.Items.Add(new ListItem("501 - 750", "300"));
            ddlCarWeight.Items.Add(new ListItem("751 - 1,000", "450"));
            ddlCarWeight.Items.Add(new ListItem("1,001 - 1,250", "800"));
            ddlCarWeight.Items.Add(new ListItem("1,251 - 1,500", "1000"));
            ddlCarWeight.Items.Add(new ListItem("1,501 - 1,750", "1300"));
            ddlCarWeight.Items.Add(new ListItem("1,751 - 2,000", "1600"));
            ddlCarWeight.Items.Add(new ListItem("2,001 - 2,500", "1900"));
            ddlCarWeight.Items.Add(new ListItem("2,501 - 3,000", "2200"));
            ddlCarWeight.Items.Add(new ListItem("3,001 - 3,500", "2400"));
            ddlCarWeight.Items.Add(new ListItem("3,501 - 4,000", "2600"));
            ddlCarWeight.Items.Add(new ListItem("4,001 - 4,500", "2800"));
            ddlCarWeight.Items.Add(new ListItem("4,501 - 5,000", "3000"));
            ddlCarWeight.Items.Add(new ListItem("5,001 - 6,000", "3200"));
            ddlCarWeight.Items.Add(new ListItem("6,001 - 7,000", "3400"));
            ddlCarWeight.Items.Add(new ListItem("> 7000", "3600"));
        }
        ddlCarWeight.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    private void ShowCustomerDetail(Int64 UserId)
    {
        CE.User.Profile _profile = new CE.User.Profile();
        CE.User.ProfileDB _profiledb = new ProfileDB();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();
        
        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            //ddlSalutation.Saluation = _profile.Salutation;
            txtName.Text = _profile.FirstName;

            if (_profile.SurName != string.Empty)
            {
                txtName.Text += " " + _profile.SurName;
            }
            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtEmailAddress.Text = _contact.Email;
                txtEmailAddress.ReadOnly = true;
                txtMobileNo.PhoneNo = _contact.Mobile;
            }

            _profile = null;
        }
    }

    //private void SetRegisterDate()
    //{
    //    if (Session["CMIREGDATE"] != null)
    //    {
    //        string dte = Session["CMIREGDATE"].ToString();
    //        if (dte.Trim().Length == 8)
    //        {
    //            //yyyyMMdd
    //            ddlManufactYear.SelectedIndex = ddlManufactYear.Items.IndexOf(ddlManufactYear.Items.FindByValue(dte.Trim().Substring(0,4)));
    //            if (ddlManufactYear.SelectedIndex > 0) ddlManufactYear_SelectedIndexChanged(null, null);
    //            int rYear = int.Parse(dte.Trim().Substring(0, 4));
    //            int rMonth = int.Parse(dte.Trim().Substring(4, 2));
    //            int rDay = int.Parse(dte.Trim().Substring(6, 2));
    //            DateTime dtNow = new DateTime(rYear, rMonth, rDay);
    //            txtRegistrationDate.Text = dtNow.ToString("dd/MMM/yyyy", CultureInfo.CurrentCulture);
    //        }
    //    }
    //}

    //private void SetCTPLDate()
    //{
    //    if (Session["CMIDATE"] != null)
    //    {
    //        string dte = Session["CMIDATE"].ToString();
    //        if (dte.Trim().Length == 8)
    //        {
    //            //ddMMyyyy
    //            int rDay = int.Parse(dte.Trim().Substring(0, 2));
    //            int rMonth = int.Parse(dte.Trim().Substring(2, 2));
    //            int rYear = int.Parse(dte.Trim().Substring(4, 4));
    //            DateTime dtNow = new DateTime(rYear, rMonth, rDay);
    //            txtCTPLDate.Text = dtNow.ToString("dd/MMM/yyyy", CultureInfo.CurrentCulture);
    //        }
    //    }
    //}

    #endregion

    #region CTPLStartDate

    //3 Months
    //คุ้มครองย้อนหลังไม่ได้ ควรระบุวันเริ่มคุ้มครองล่วงหน้าอย่างน้อย 1-2 วัน
    private void SetCTPLStartDate()
    {
        CultureInfo ci = CultureInfo.CurrentCulture;
        DateTime dtNow = new DateTime();
        dtNow = DateTime.Now.AddDays(2);

        DateTime dtEndMonth = new DateTime();
        dtEndMonth = DateTime.Now.AddDays(90);

        int mthDiff = ((dtEndMonth.Year - dtNow.Year) * 12) + dtEndMonth.Month - dtNow.Month;
        for (int m = 0; m <= mthDiff; m++)
        {
            DateTime dtTemp = dtNow.AddMonths(m);
            string strDate = dtTemp.ToString("MMyyyy", new CultureInfo("en-US"));
            ddlCTPLStartMonth.Items.Add(new ListItem(dtTemp.ToString("MMMM yyyy", ci), strDate));
        }

        //DateTime dtNow2 = new DateTime();
        //dtNow2 = DateTime.Now.AddDays(14);
        //if (dtNow2.Month == dtNow.Month)
        //{
        //    DateTime dtEnd = new DateTime();
        //    dtEnd = new DateTime(dtNow.Year, dtNow.Month, DateTime.DaysInMonth(dtNow.Year, dtNow.Month));
        //    int dteDiff = dtEnd.Day - dtNow.Day;
        //    for (int i = 0; i <= dteDiff; i++)
        //    {
        //        DateTime dtTemp = dtNow.AddDays(i);
        //        string strDate = dtTemp.Date.Day.ToString("00");
        //        ddlCTPLStartDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strDate));
        //    }
        //}
        //else
        //{
        //    DateTime dtEnd = new DateTime();
        //    dtEnd = new DateTime(dtNow2.Year, dtNow2.Month, DateTime.DaysInMonth(dtNow2.Year, dtNow2.Month));
        //    dtNow = new DateTime(dtNow2.Year, dtNow2.Month, 1);
        //    int dteDiff = dtEnd.Day - 1;
        //    for (int i = 0; i <= dteDiff; i++)
        //    {
        //        DateTime dtTemp = dtNow.AddDays(i);
        //        string strDate = dtTemp.Date.Day.ToString("00");
        //        ddlCTPLStartDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strDate));
        //    }
        //}

        for (int i = 1; i <= 31; i++)
        {
            string strDate = i.ToString().PadLeft(2, '0');
            ddlCTPLStartDay.Items.Add(new ListItem(strDate, strDate));
        }

        ddlCTPLStartDay.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlCTPLStartMonth.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlCTPLStartMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        CultureInfo ci = CultureInfo.CurrentCulture;
        string selDate = ddlCTPLStartDay.Text;
        ddlCTPLStartDay.Items.Clear();
        string selMonth = ddlCTPLStartMonth.Text;
        if (selMonth.Length > 5)
        {
            int _iMonth = Convert.ToInt32(selMonth.Substring(0, 2));
            int _iYear = Convert.ToInt32(selMonth.Substring(2, 4));

            DateTime dtNow = new DateTime();
            dtNow = DateTime.Now.AddDays(2);

            DateTime dtEnd = new DateTime();
            dtEnd = new DateTime(_iYear, _iMonth, DateTime.DaysInMonth(_iYear, _iMonth));

            DateTime dtEndMonth = new DateTime();
            dtEndMonth = DateTime.Now.AddDays(120);

            if (dtNow.Month == _iMonth && dtNow.Year == _iYear)
            {
                //Start
                int dteDiff = dtEnd.Day - dtNow.Day;
                for (int i = 0; i <= dteDiff; i++)
                {
                    DateTime dtTemp = dtNow.AddDays(i);
                    string strTemp = dtTemp.Date.Day.ToString("00");
                    ddlCTPLStartDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strTemp));
                }
            }
            else if (dtEndMonth.Month == _iMonth && dtEndMonth.Year == _iYear)
            {
                //End
                dtNow = new DateTime(_iYear, _iMonth, 1);

                int dteDiff = dtEndMonth.Day - 1;
                for (int i = 0; i <= dteDiff; i++)
                {
                    DateTime dtTemp = dtNow.AddDays(i);
                    string strTemp = dtTemp.Date.Day.ToString("00");
                    ddlCTPLStartDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strTemp));
                }
            }
            else
            {
                dtNow = new DateTime(_iYear, _iMonth, 1);

                int dteDiff = dtEnd.Day - 1;
                for (int i = 0; i <= dteDiff; i++)
                {
                    DateTime dtTemp = dtNow.AddDays(i);
                    string strTemp = dtTemp.Date.Day.ToString("00");
                    ddlCTPLStartDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strTemp));
                }
            }

            ddlCTPLStartDay.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
            ddlCTPLStartDay.SelectedIndex = ddlCTPLStartDay.Items.IndexOf(ddlCTPLStartDay.Items.FindByValue(selDate));
        }
    }

    #endregion

    #region RegistrationDate

    //Tax renewal not more than 7 years
    private void RegistrationDate()
    {
        CultureInfo ci = CultureInfo.CurrentCulture;

        int yerDiff = 7;
        for (int y = 1; y < yerDiff; y++)
        {
            DateTime dtTemp = DateTime.Now.AddYears(-y);
            string strDate = dtTemp.ToString("yyyy", new CultureInfo("en-US"));
            ddlRegistrationYear.Items.Add(new ListItem(dtTemp.ToString("yyyy", ci), strDate));
        }

        int mthDiff = 12;
        for (int m = 0; m < mthDiff; m++)
        {
            DateTime dtTemp = new DateTime(DateTime.Now.Year, 1 + m, 1);
            string strDate = dtTemp.ToString("MM", new CultureInfo("en-US"));
            ddlRegistrationMonth.Items.Add(new ListItem(dtTemp.ToString("MMMM", ci), strDate));
        }


        int dteDiff = 31;
        for (int i = 1; i <= dteDiff; i++)
        {
            string strDate = i.ToString("00");
            ddlRegistrationDay.Items.Add(new ListItem(strDate, strDate));
        }

        ddlRegistrationDay.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlRegistrationMonth.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlRegistrationYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlRegistrationMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selDate = ddlRegistrationDay.Text;
        CultureInfo ci = CultureInfo.CurrentCulture;
        string strMonth = ddlRegistrationMonth.Text;
        string strYear = ddlRegistrationYear.Text;
        int _iMonth = Convert.ToInt32(strMonth);
        int _iYear = Convert.ToInt32(strYear);

        if (_iYear != -1 && _iMonth != -1)
        {
            ddlRegistrationDay.Items.Clear();
            DateTime dtNow = new DateTime();
            dtNow = DateTime.Now.AddDays(2);

            DateTime dtEnd = new DateTime();
            dtEnd = new DateTime(_iYear, _iMonth, DateTime.DaysInMonth(_iYear, _iMonth));

            DateTime dtEndMonth = new DateTime();
            dtEndMonth = DateTime.Now.AddDays(120);

            if (dtNow.Month == _iMonth && dtNow.Year == _iYear)
            {
                //Start
                int dteDiff = dtEnd.Day - dtNow.Day;
                for (int i = 1; i <= dteDiff; i++)
                {
                    DateTime dtTemp = dtNow.AddDays(i);
                    string strTemp = dtTemp.Date.Day.ToString("00");
                    ddlRegistrationDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strTemp));
                }
            }
            else if (dtEndMonth.Month == _iMonth && dtEndMonth.Year == _iYear)
            {
                //End
                dtNow = new DateTime(_iYear, _iMonth, 1);

                int dteDiff = dtEndMonth.Day - 1;
                for (int i = 1; i <= dteDiff; i++)
                {
                    DateTime dtTemp = dtNow.AddDays(i);
                    string strTemp = dtTemp.Date.Day.ToString("00");
                    ddlRegistrationDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strTemp));
                }
            }
            else
            {
                dtNow = new DateTime(_iYear, _iMonth, 1);

                int dteDiff = dtEnd.Day - 1;
                for (int i = 1; i <= dteDiff; i++)
                {
                    DateTime dtTemp = dtNow.AddDays(i);
                    string strTemp = dtTemp.Date.Day.ToString("00");
                    ddlRegistrationDay.Items.Add(new ListItem(dtTemp.ToString("dd", ci), strTemp));
                }
            }

            ddlRegistrationDay.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
            ddlRegistrationDay.SelectedIndex = ddlRegistrationDay.Items.IndexOf(ddlRegistrationDay.Items.FindByValue(selDate));
        }
    }

    #endregion

    #region ExpiryMonth

    //private void ExpiryMonth()
    //{
    //    CultureInfo ci = CultureInfo.CurrentCulture;
    //    int mthDiff = 12;
    //    for (int m = 0; m < mthDiff; m++)
    //    {
    //        DateTime dtTemp = new DateTime(DateTime.Now.Year, 1 + m, 1);
    //        string strDate = dtTemp.ToString("MM", new CultureInfo("en-US"));
    //        ddlExpiryMonth.Items.Add(new ListItem(dtTemp.ToString("MMMM", ci), strDate));
    //    }
    //    ddlExpiryMonth.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    //}

    #endregion

    #region Insurance

    //private void GetInsurance()
    //{
    //    try
    //    {
    //        //MyDatabase _db = new MyDatabase();
    //        DataTable dtC;
    //        //if (System.Globalization.CultureInfo.CurrentCulture.Name == "th-TH")
    //        //{
    //        //    dtC = _db.GetDataTable("SELECT THCompanyNameDescription AS CompanyName, ProviderCompanyId FROM tblProviderCompany Where [Status] = 1 ORDER BY THCompanyNameDescription ");
    //        //}
    //        //else
    //        //{
    //        //    dtC = _db.GetDataTable("SELECT CompanyNameDescription AS CompanyName, ProviderCompanyId FROM tblProviderCompany Where [Status] = 1 ORDER BY CompanyNameDescription ");
    //        //}

    //        dtC = General.GetComboItem(Resources.DBTable.PreInsurer, Resources.DBTable.OrderByField, true);
    //        ddlInsurance.DataSource = dtC;
    //        ddlInsurance.DataTextField = dtC.Columns[0].ColumnName.ToString();
    //        ddlInsurance.DataValueField = dtC.Columns[1].ColumnName.ToString();
    //        ddlInsurance.DataBind();

    //        ddlInsurance.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    //    }
    //    catch (Exception ex)
    //    {
    //    }
    //}

    #endregion

    #region CarColor

    private void GetCarColorTH()
    {
        //string[] color = {"ขาว","เขียว","ชมพู","ดำ","แดง","ทอง","เทา","น้ำตาล","น้ำเงิน","บรอนซ์",
        //                     "ฟ้า","ม่วง","ส้ม","เหลือง","บรอนซ์เงิน","บรอนซ์ทอง"};
        //ddlColor.DataSource = color;
        //ddlColor.DataBind();

        ddlColor.Items.Add(new ListItem("ขาว", "ขาว"));
        ddlColor.Items.Add(new ListItem("เขียว", "เขียว"));
        ddlColor.Items.Add(new ListItem("ชมพู", "ชมพู"));
        ddlColor.Items.Add(new ListItem("ดำ", "ดำ"));
        ddlColor.Items.Add(new ListItem("แดง", "แดง"));
        ddlColor.Items.Add(new ListItem("ทอง", "ทอง"));
        ddlColor.Items.Add(new ListItem("เทา", "เทา"));
        ddlColor.Items.Add(new ListItem("น้ำตาล", "น้ำตาล"));
        ddlColor.Items.Add(new ListItem("น้ำเงิน", "น้ำเงิน"));
        ddlColor.Items.Add(new ListItem("บรอนซ์", "บรอนซ์"));
        ddlColor.Items.Add(new ListItem("ฟ้า", "ฟ้า"));
        ddlColor.Items.Add(new ListItem("ม่วง", "ม่วง"));
        ddlColor.Items.Add(new ListItem("ส้ม", "ส้ม"));
        ddlColor.Items.Add(new ListItem("เหลือง", "เหลือง"));
        ddlColor.Items.Add(new ListItem("บรอนซ์เงิน", "บรอนซ์เงิน"));
        ddlColor.Items.Add(new ListItem("บรอนซ์ทอง", "บรอนซ์ทอง"));

        ddlColor.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    private void GetCarColorEN()
    {
        //string[] color = {"White","Green","Pink","Black","Red","Golden","Gray","Brown","Blue","Bronze",
        //                     "Light blue","Purple","Orange","Yellow","Silver","Golden bronze"};
        //ddlColor.DataSource = color;
        //ddlColor.DataBind();

        ddlColor.Items.Add(new ListItem("White", "ขาว"));
        ddlColor.Items.Add(new ListItem("Green", "เขียว"));
        ddlColor.Items.Add(new ListItem("Pink", "ชมพู"));
        ddlColor.Items.Add(new ListItem("Black", "ดำ"));
        ddlColor.Items.Add(new ListItem("Red", "แดง"));
        ddlColor.Items.Add(new ListItem("Golden", "ทอง"));
        ddlColor.Items.Add(new ListItem("Gray", "เทา"));
        ddlColor.Items.Add(new ListItem("Brown", "น้ำตาล"));
        ddlColor.Items.Add(new ListItem("Blue", "น้ำเงิน"));
        ddlColor.Items.Add(new ListItem("Bronze", "บรอนซ์"));
        ddlColor.Items.Add(new ListItem("Light blue", "ฟ้า"));
        ddlColor.Items.Add(new ListItem("Purple", "ม่วง"));
        ddlColor.Items.Add(new ListItem("Orange", "ส้ม"));
        ddlColor.Items.Add(new ListItem("Yellow", "เหลือง"));
        ddlColor.Items.Add(new ListItem("Silver", "บรอนซ์เงิน"));
        ddlColor.Items.Add(new ListItem("Golden bronze", "บรอนซ์ทอง"));

        ddlColor.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    #endregion

    #region Car

    private void LoadManufactYearList()
    {
        int _yearCount = 19;
        ddlManufactYear.Items.Clear();

        int _startYear = DateTime.Now.Year - _yearCount;
        int _endYear = DateTime.Now.Year;
        for (int i = _endYear; i >= _startYear; i--)
        {
            //ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            if (CultureInfo.CurrentCulture.Name != "th-TH")
            {
                ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            else
            {
                ddlManufactYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
            }
        }
        ddlManufactYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlManufactYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string carMakeValue = ddlCarMake.Text;
            string carModelValue = ddlModelBodyCCDoor.Text;

            if (ddlManufactYear.Text == "-1")
            {
                ClearAllList();
            }
            else
            {
                GetCarMakeList(ddlManufactYear.Text, ddlCarMake);
                if (ddlCarMake.Items.Count > 0)
                {
                    if (carMakeValue != "-1")
                    {
                        ddlCarMake.Text = carMakeValue;
                        ddlCarMake_SelectedIndexChanged(sender, e);

                        if (carModelValue != "-1" && ddlModelBodyCCDoor.Items.Count > 0)
                        {
                            ddlModelBodyCCDoor.Text = carModelValue;
                            ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
                        }
                    }
                    else
                    {

                    }
                }
            }
        }
        catch
        {

        }
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        //System.Threading.Thread.Sleep(10000);
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

            txtSumInsured.Text = "0";
            lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlManufactYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }
        }
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        //ddlCarMake.Items.Add(new ListItem("Test", "TEST"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelDescTHListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                //ddlList.Items.Add(new ListItem(_dt.Rows[i][0].ToString()));
                ddlList.DataSource = _dt;
                ddlList.DataValueField = "CarModelDesc";
                ddlList.DataTextField = "CarModelDisplay";
                ddlList.DataBind();
                ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
            }
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        _dt = null;
        _db = null;
    }

    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlManufactYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            txtEngineSize.Text = _cc;
            //ChangeVehicleUsageList(lblCarVehicleType.Text);
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
            //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Init_JTip_Driver", "JT_init();", true);
            //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ShowHide_AccMod", "CheckAccMod();", true);
            //CheckAccMod()
        }
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
            //txtTextBox.Text = string.Format("{0:#,0}", _dt.Rows[0][0]);
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    #endregion

    #region Province

    private void GetProvinceTH()
    {
        string[] provinces = {"กระบี่","กรุงเทพมหานครฯ","กาญจนบุรี","กาฬสินธุ์","กำแพงเพชร","ขอนแก่น","จันทบุรี","ฉะเชิงเทรา","ชลบุรี","ชัยนาท",
                            "ชัยภูมิ","ชุมพร","เชียงราย","เชียงใหม่","ตรัง","ตราด","ตาก","นครนายก","นครปฐม","นครพนม",
                            "นครราชสีมา","นครศรีธรรมราช","นครสวรรค์","นนทบุรี","นราธิวาส","น่าน","บึงกาฬ","บุรีรัมย์","ปทุมธานี","ประจวบคีรีขันธ์",
                            "ปราจีนบุรี","ปัตตานี","พระนครศรีอยุธยา","พะเยา","พังงา","พัทลุง","พิจิตร","พิษณุโลก","เพชรบุรี","เพชรบูรณ์",
                            "แพร่","ภูเก็ต","มหาสารคาม","มุกดาหาร","แม่ฮ่องสอน","ยโสธร","ยะลา","ร้อยเอ็ด","ระนอง","ระยอง",
                            "ราชบุรี","ลพบุรี","ลำปาง","ลำพูน","เลย","ศรีสะเกษ","สกลนคร","สงขลา","สตูล","สมุทรปราการ",
                            "สมุทรสงคราม","สมุทรสาคร","สระแก้ว","สระบุรี","สิงห์บุรี","สุโขทัย","สุพรรณบุรี","สุราษฎร์ธานี","สุรินทร์","หนองคาย",
                            "หนองบัวลำภู","อ่างทอง","อำนาจเจริญ","อุดรธานี","อุตรดิตถ์","อุทัยธานี","อุบลราชธานี"};
        ddlProvince.DataSource = provinces;
        ddlProvince.DataBind();

        ddlProvince.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    private void GetProvinceEN()
    {
        string[] provinces = {"Amnat Charoen","Ang Thong","Bangkok","Bueng Kan","Buri Ram","Chachoengsao","Chai Nat","Chaiyaphum","Chanthaburi","Chiang Mai",
                            "Chiang Rai","Chon Buri","Chumphon","Kalasin","Kamphaeng Phet","Kanchanaburi","Khon Kaen","Krabi","Lampang","Lamphun",
                            "Loei","Lop Buri","Mae Hong Son","Maha Sarakham","Mukdahan","Nakhon Nayok","Nakhon Pathom","Nakhon Phanom","Nakhon Ratchasima","Nakhon Sawan",
                            "Nakhon Si Thammarat","Nan","Narathiwat","Nong Bua Lam Phu","Nong Khai","Nonthaburi","Pathum Thani","Pattani","Phangnga","Phatthalung",
                            "Phayao","Phetchabun","Phetchaburi","Phichit","Phitsanulok","Phra Nakhon Si Ayutthaya","Phrae","Phuket","Prachin Buri","Prachuap Khiri Khan",
                            "Ranong","Ratchaburi","Rayong","Roi Et","Sa Kaeo","Sakon Nakhon","Samut Prakan","Samut Sakhon","Samut Songkhram","Saraburi",
                            "Satun","Si Sa Ket","Sing Buri","Songkhla","Sukhothai","Suphan Buri","Surat Thani","Surin","Tak","Trang",
                            "Trat","Ubon Ratchathani","Udon Thani","Uthai Thani","Uttaradit","Yala","Yasothon"};
        ddlProvince.DataSource = provinces;
        ddlProvince.DataBind();

        ddlProvince.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    #endregion

    #region FillIn

    private void FillIn()
    {
        CMI _cmi = new CMI();
        CMIDB _cmidb = new CMIDB();
        _cmi = _cmidb.GetCMI(Convert.ToInt64(Session[General.CMIId]));

        Session["CMICARTYPE"] = _cmi.CarType;
        hidCarType.Value = _cmi.CarType.ToString();
        Session["CMIPROVIDER"] = _cmi.CTPLProviderCompanyId;
        Session[General.CMICarId] = _cmi.CECarId;
        hidCMIType.Value = _cmi.ServiceType.ToString();

        if (_cmi.ServiceType == '2')
        {
            chkTax.Checked = true;
        }
        else if (_cmi.ServiceType == '3')
        {
            divCMIDetail.Style.Add("display", "none");
            chkTax.Checked = true;
            rfvChassisNo.Enabled = false;
            rfvColor.Enabled = false;
            rfvEngineSize.Enabled = false;
            rfvCTPLStartDay.Enabled = false;
            rfvCTPLStartMonth.Enabled = false;
        }

        if (_cmi.CMIDate != null)
        {
            string strDate = _cmi.CMIDate.Value.ToString("MMyyyy", new CultureInfo("en-US"));
            ddlCTPLStartMonth.SelectedIndex = ddlCTPLStartMonth.Items.IndexOf(ddlCTPLStartMonth.Items.FindByValue(strDate));
            ddlCTPLStartMonth_SelectedIndexChanged(null, null);
            ddlCTPLStartDay.SelectedIndex = ddlCTPLStartDay.Items.IndexOf(ddlCTPLStartDay.Items.FindByValue(_cmi.CMIDate.Value.ToString("dd")));
        }

        hidCarType.Value = _cmi.CarType.ToString();
        if (_cmi.RegistrationDate != null)
        {
            chkTax.Checked = true;
            string strDate = _cmi.RegistrationDate.Value.ToString("yyyy", new CultureInfo("en-US"));
            ddlRegistrationYear.SelectedIndex = ddlRegistrationYear.Items.IndexOf(ddlRegistrationYear.Items.FindByValue(strDate));
            ddlRegistrationMonth.SelectedIndex = ddlRegistrationMonth.Items.IndexOf(ddlRegistrationMonth.Items.FindByValue(_cmi.RegistrationDate.Value.ToString("MM")));
            ddlRegistrationMonth_SelectedIndexChanged(null, null);
            ddlRegistrationDay.SelectedIndex = ddlRegistrationDay.Items.IndexOf(ddlRegistrationDay.Items.FindByValue(_cmi.RegistrationDate.Value.ToString("dd")));

            if (_cmi.CarWeight.Trim() != "")
            {
                divCarWeight.Style.Add("display", "");

                if (hidCarType.Value != "1")
                {
                    SetupCarWeight();
                }
                ddlCarWeight.SelectedIndex = ddlCarWeight.Items.IndexOf(ddlCarWeight.Items.FindByText(_cmi.CarWeight));
            }
        }

        if (hidCarType.Value == "1")
        {
            rfvEngineSize.Enabled = true;
        }
        else
        {
            rfvCarWeight.Enabled = true;
        }

        if (_cmi.CTPLAmout > 0) lblSumCTPL.Text = _cmi.CTPLAmout.ToString();
        if (_cmi.CTPLDiscount > 0) lblSumDiscount.Text = _cmi.CTPLDiscount.ToString();
        if (_cmi.TaxRenewalAmount > 0)
        {
            lblSumTaxAndPanalty.Text = _cmi.TaxRenewalAmount.ToString();
            hidCalTaxAndPanalty.Value = _cmi.TaxRenewalAmount.ToString();
        }
        if (_cmi.ChargedAmount > 0)
        {
            lblSumCharged.Text = _cmi.ChargedAmount.ToString();
            hidSumCharged.Value = _cmi.ChargedAmount.ToString();
        }
        if (_cmi.EMS > 0)
        {
            rdlDeliveryMethod.SelectedIndex = 1;
            lblSumEMS.Text = _cmi.EMS.ToString();
            hidSumEMS.Value = _cmi.EMS.ToString();
        }
        if (_cmi.CMITotal > 0)
        {
            lblTotal.Text = _cmi.CMITotal.ToString();
            hidTotal.Value = _cmi.CMITotal.ToString();
        }

        ddlManufactYear.SelectedIndex = ddlManufactYear.Items.IndexOf(ddlManufactYear.Items.FindByValue(_cmi.ManufactYear.ToString()));
        ddlManufactYear_SelectedIndexChanged(null, null);
        ddlCarMake.Text = _cmi.CarMake;
        ddlCarMake_SelectedIndexChanged(null, null);
        string _tempDesc = _cmi.CarModel + " " + _cmi.Body + " " + _cmi.CC + "cc " + _cmi.Door.ToString() + " doors";
        ddlModelBodyCCDoor.Text = _tempDesc;
        ddlModelBodyCCDoor_SelectedIndexChanged(null, null);

        txtChassisNo.Text = _cmi.ChassisNo;
        txtEngineNumber.Text = _cmi.EngineNumber;
        txtEngineSize.Text = _cmi.EngineSize;

        ddlColor.SelectedIndex = ddlColor.Items.IndexOf(ddlColor.Items.FindByValue(_cmi.CarColor));

        txtName.Text = _cmi.Name;
        txtOwnerName.Text = _cmi.OwnerName;
        txtPlateNumber.Text = _cmi.CarPlate;
        ddlProvince.SelectedIndex = ddlProvince.Items.IndexOf(ddlProvince.Items.FindByValue(_cmi.Province));
        txtAddress.Text = _cmi.Address;
        txtEmailAddress.Text = _cmi.Email;
        txtMobileNo.PhoneNo = _cmi.Mobile;
        chkCopyAddress.Checked = _cmi.IsSameAddress;
        if (_cmi.IsSameAddress)
        {
            txtDeliveryAddress.Text = "";
            txtDeliveryName.Text = "";
        }
        else
        {
            txtDeliveryAddress.Text = _cmi.DeliveryAddress;
            txtDeliveryName.Text = _cmi.DeliveryName;
        }
       
        // PaymentType
        //if (_cmi.ProviderCompanyId > 0) ddlInsurance.SelectedIndex = ddlInsurance.Items.IndexOf(ddlInsurance.Items.FindByValue(_cmi.ProviderCompanyId.ToString()));
        //if (_cmi.ExpiryMonth.ToString().Trim() != "") ddlExpiryMonth.SelectedIndex = ddlExpiryMonth.Items.IndexOf(ddlExpiryMonth.Items.FindByValue(_cmi.ExpiryMonth.ToString()));        
    }

    #endregion

    #region Save

    protected void btnNext_Click(object sender, EventArgs e)
    {
        ChangeValidationEffectServerSide("carprofile");
        //Page.Validate("carprofile");
        CheckValidation();
        if (Page.IsValid)
        {
            bool _IsEmailExist = false;

            if (Session[General.UserId] == null)
            {
                Account _useraccount = new Account();
                AccountDB _useraccountdb = new AccountDB();

                if (_useraccountdb.IsAlreadyExist(EmailAddress, Convert.ToInt32(CE.Global.CEUserType.Customer))) //txtEmailAddress.Text.Trim()
                {
                    txtEmailAddress.ControlStyle.CssClass = "validationError";
                    lblMessage.Text = "";
                    vsCarProfile.Enabled = false;
                    _IsEmailExist = true;
                    mpePassword.Show();
                    return;
                }
            }
            vsCarProfile.Enabled = true;
            if (_IsEmailExist == false && Save())
            {
                Int64 _userId = 0;
                Int64 _carId = Convert.ToInt64(Session[General.CMICarId].ToString());
                bool _newuser = false;
                if (Session[General.UserId] != null)
                {
                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                }
                else
                {
                    _newuser = true;
                }

                if (UpdateProfile(_userId, _carId) > 0)
                {
                    //lblSortBy.Text = ddlSortBy.Text;
                    if (_newuser)
                    {
                        //SendMailToUser(EmailAddress, Session[CE.Global.General.UserName].ToString(), txtMobileNo.GetPhoneNo()); //txtEmailAddress.Text.Trim()
                    }

                    lblMessage.Text = "Saved successfully!";
                }
                else
                {
                    //popup login
                    //Page.ClientScript.RegisterClientScriptBlock(pnlPassword.GetType(), "poplogin", "", true);
                    lblMessage.Text = "";
                    vsCarProfile.Enabled = false;
                    mpePassword.Show();
                }
            }

            // ************* CMI ****************
            
            CMI _cmi = new CMI();
            CMIDB _cmidb = new CMIDB();
            if (Session[General.CMIId] != null) _cmi = _cmidb.GetCMI(Convert.ToInt64(Session[General.CMIId]));

            if (Session[CE.Global.General.UserId] != null) _cmi.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.UserId]);

            _cmi.ServiceType = '1';
            if (chkTax.Checked)
            {
                _cmi.ServiceType = '2';
                if (hidCMIType.Value == "3") _cmi.ServiceType = '3';
            }
            _cmi.CarType = Convert.ToChar(hidCarType.Value);
            if (Session["CMIPROVIDER"] != null)
            {
                _cmi.CTPLProviderCompanyId = Convert.ToInt64(Session["CMIPROVIDER"]);
                Session[General.ProviderCompanyId] = Convert.ToInt64(Session["CMIPROVIDER"]);
            }
            else
            {
                _cmi.CTPLProviderCompanyId = 0;
                Session[General.ProviderCompanyId] = 0;
            }
            
            _cmi.CECarId = Convert.ToInt64(Session[General.CMICarId].ToString());

            if (ddlCTPLStartDay.Text != "-1")
            {
                string strDate = ddlCTPLStartDay.Text;
                int _iDay = Convert.ToInt32(strDate.Substring(0, 2));
                strDate = ddlCTPLStartMonth.Text;
                int _iMonth = Convert.ToInt32(strDate.Substring(0, 2));
                int _iYear = Convert.ToInt32(strDate.Substring(2, 4));
                _cmi.CMIDate = new DateTime(_iYear, _iMonth, _iDay);
            }

            if (chkTax.Checked)
            {
                int _rDay = Convert.ToInt32(ddlRegistrationDay.Text);
                int _rMonth = Convert.ToInt32(ddlRegistrationMonth.Text);
                int _rYear = Convert.ToInt32(ddlRegistrationYear.Text);
                _cmi.RegistrationDate = new DateTime(_rYear, _rMonth, _rDay);

                if (hidCarType.Value != "1")
                {
                    if (ddlCarWeight.Text != "-1")
                    {
                        _cmi.CarWeight = ddlCarWeight.SelectedItem.Text;
                    }
                }
            }

            if (Session[CE.Global.General.UserId] != null)
            {
                _cmi.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.UserId]);
            }
            //UPDATE tblCMIDetail SET ModifiedDate = 'CMI' + CONVERT(NVARCHAR(100),(100000 + @ReturnValue))
            if (lblSumCTPL.Text.Trim() != "") _cmi.CTPLAmout = Convert.ToDecimal(lblSumCTPL.Text);
            if (lblSumDiscount.Text.Trim() != "") _cmi.CTPLDiscount = Convert.ToDecimal(lblSumDiscount.Text);
            if (hidCalTaxAndPanalty.Value.Trim() != "") _cmi.TaxRenewalAmount = Convert.ToDecimal(hidCalTaxAndPanalty.Value);
            if (hidSumCharged.Value.Trim() != "") _cmi.ChargedAmount = Convert.ToDecimal(hidSumCharged.Value);
            if (hidSumEMS.Value.Trim() != "") _cmi.EMS = Convert.ToDecimal(hidSumEMS.Value);
            if (hidTotal.Value.Trim() != "") _cmi.CMITotal = Convert.ToDecimal(hidTotal.Value);
            _cmi.CarMake = ddlCarMake.Text;
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            if (_tempDesc.Length == 5)
            {
                _cmi.CarModel = _tempDesc[0];
                _cmi.Body = _tempDesc[1];
                _cmi.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
                _cmi.Door = Convert.ToInt32(_tempDesc[3]);
            }
            else if (_tempDesc.Length == 6)
            {
                _cmi.CarModel = _tempDesc[0] + " " + _tempDesc[1];
                _cmi.Body = _tempDesc[2];
                _cmi.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
                _cmi.Door = Convert.ToInt32(_tempDesc[4]);
            }
            else if (_tempDesc.Length == 7)
            {
                _cmi.CarModel = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _cmi.Body = _tempDesc[3];
                _cmi.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
                _cmi.Door = Convert.ToInt32(_tempDesc[5]);
            }
            _cmi.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);
            _cmi.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
            _cmi.ChassisNo = txtChassisNo.Text;
            _cmi.EngineNumber = txtEngineNumber.Text;
            _cmi.EngineSize = txtEngineSize.Text;

            if (ddlColor.SelectedValue != "-1") _cmi.CarColor = ddlColor.SelectedValue;

            _cmi.Name = txtName.Text;
            _cmi.OwnerName = txtOwnerName.Text;
            _cmi.CarPlate = txtPlateNumber.Text;
            _cmi.Province = ddlProvince.SelectedItem.Text;
            _cmi.Address = txtAddress.Text;
            _cmi.Email = EmailAddress.ToLower();
            _cmi.Mobile = txtMobileNo.PhoneNo;
            _cmi.IsSameAddress = chkCopyAddress.Checked;
            if (chkCopyAddress.Checked)
            {
                _cmi.DeliveryAddress = txtAddress.Text;
                _cmi.DeliveryName = txtName.Text;
            }
            else
            {
                _cmi.DeliveryAddress = txtDeliveryAddress.Text;
                _cmi.DeliveryName = txtDeliveryName.Text;
            }
            if (System.Globalization.CultureInfo.CurrentCulture.Name == "th-TH")
            {
                _cmi.IsEnglish = false;
            }
            else
            {
                _cmi.IsEnglish = true;
            }
            // PaymentType
            //if (ddlInsurance.SelectedValue != "-1") _cmi.ProviderCompanyId = Convert.ToInt64(ddlInsurance.SelectedValue);
            //if (ddlExpiryMonth.SelectedValue != "-1") _cmi.ExpiryMonth = ddlExpiryMonth.SelectedValue;
            _cmi.Status = "NEW";
            long resultVal = _cmidb.InsertUpdate(_cmi);

            if (resultVal != -1)
            {
                lblMessage.Text = "Saved successfully!";
                Session["CMITYPE"] = null;
                Session["CMICARTYPE"] = null;
                Session["CMIPROVIDER"] = null;
                Session["CMITITLE"] = null;
                Session["CMICTPL"] = null;
                Session["CMICTPLDISC"] = null;
                Session["CMITOTAL"] = null;
                Session["CMIINSURER"] = null;
                Session[General.CMIId] = resultVal;
                string _url = CE.Global.General.GetUrl("~/car-insurance/proposalforms/cmi_form.aspx", Page);
                Response.Redirect(_url);
            }
            else
            {
                lblMessage.Text = "Saving did NOT succeed!";
            }
        }
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();

            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; // ddlSalutation.GetSalutation();
                txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text.Trim());
                _profile.FirstName = HttpUtility.HtmlEncode(txtName.Text);
                _profile.SurName = ""; //txtSurName.Text;
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M'; //Convert.ToChar(ddlGender.GetGender());
                }
                //_profile.MaritalStatus = -1;// Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                //_profile.JobNature = "";// ddlJobNature.GetJobNature();
                //_profile.Occupation = 54; //Convert.ToInt32(ddlOccupation.GetOccupation());
                //_profile.YearDriveSg = 0;//Convert.ToInt16(ddlYearDriveSg.Text);
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobileNo.GetPhoneNo();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                    //divNewErrorMessage.Visible = true;
                    //lblCarInsProfileMessage.Text = "Error found in profile update!";
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[General.UserPhoneNo] = txtMobileNo.GetPhoneNo();
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }
                else
                {
                    //divNewErrorMessage.Visible = true;
                    //lblCarInsProfileMessage.Text = "Error found in contact update!";
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        if (_retValue > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);


            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();
            _profile = _profiledb.GetProfile(UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = EmailAddress; //txtEmailAddress.Text;
                _cardetail.Info6 = txtMobileNo.GetPhoneNo();
                _cardetail.Info7 = ""; //txtSurName.Text.Trim();
                txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text.Trim());
                if (txtName.Text.Trim().Length > 0)
                {
                    _cardetail.Info8 = Server.HtmlEncode(txtName.Text.Trim());
                }
                //CultureInfo ci = CultureInfo.CurrentCulture;
                if (_profile.Gender.ToString().Trim() != "")
                {
                    _cardetail.Info9 = _profile.Gender.ToString(); //ddlGender.GetGender();
                }
                else
                {
                    _cardetail.Info9 = "M"; //ddlGender.GetGender();
                }
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _cardetail.Info10 = dteDOB.ToString("dd-MMM-yyyy"); //usrDOB.GetDate().ToString("dd-MMM-yyyy");
                }
                else
                {
                    _cardetail.Info10 = _profile.DOB.ToString("dd-MMM-yyyy");
                }
                _cardetail.Info11 = _profile.Occupation.ToString(); //Resources.CarInsurance.CorporateEmployee; //ddlOccupation.GetOccupation();
                _cardetail.Info12 = "";// ddlJobNature.GetJobNature();
                _cardetail.Info13 = "";// ddlMaritalStatus.GetMaritalStatus();
                _cardetail.Info14 = "";// ddlYearDriveSg.Text;
                _cardetail.Info15 = "";// ddlSalutation.GetSalutation();
                _cardetail.RefCEUserId = UserId;
            }
            _profile = null;

            //RefUserId only update
            //CarPolicy _carpolicy = new CarPolicy();
            //CarPolicyDB _carpolicydb = new CarPolicyDB();
            //_carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            //_carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            //_retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            //CarDetailTHDB cardb = new CarDetailTHDB();
            //cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
                //divNewErrorMessage.Visible = true;
                //lblCarInsProfileMessage.Text = "Error found in car quote profile update";
            }
        }

        return _retValue;
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            if (_useraccountdb.IsAlreadyExist(EmailAddress, Convert.ToInt32(CE.Global.CEUserType.Customer))) //txtEmailAddress.Text.Trim()
            {
                //divNewErrorMessage.Visible = true;
                //lblCarInsProfileMessage.Text = "Email address is already registered!";
                txtEmailAddress.ControlStyle.CssClass = "validationError";
                _retVal = 0;
            }
            else
            {
                Profile _userprofile = new Profile();
                ProfileDB _userprofiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                long _result = -1;
                //divNewErrorMessage.Visible = false;
                //lblCarInsProfileMessage.Visible = false;

                _useraccount.Email = EmailAddress.ToLower(); //txtEmailAddress.Text.ToLower();

                //Random _random = new Random();
                string _authcode = txtMobileNo.GetPhoneNo();
                //Sakthi on 21 Jan 2011
                //_authcode = "C" + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();
                //_authcode = _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();

                _useraccount.AuthCode = _authcode;

                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;

                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;

                if (_result > 0)
                {
                    _userprofile.Salutation = ""; //ddlSalutation.GetSalutation();
                    _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                    _userprofile.SurName = "";

                    //DateTime _dtDOB = new DateTime(1900, 1, 1);
                    //_userprofile.DOB = _dtDOB;
                    //_userprofile.DOB = usrDOB.GetDate();
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M'; //Convert.ToChar(ddlGender.GetGender());

                    _userprofile.Occupation = Convert.ToInt32("54");
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobileNo.GetPhoneNo();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        //SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = DateTime.Now.ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private void CheckValidation()
    {
        txtName.Text = General.ClearScriptTag(txtName.Text);
        txtOwnerName.Text = General.ClearScriptTag(txtOwnerName.Text);
        txtDeliveryName.Text = General.ClearScriptTag(txtDeliveryName.Text);
        txtAddress.Text = General.ClearScriptTag(txtAddress.Text);
        txtChassisNo.Text = General.ClearScriptTag(txtChassisNo.Text);
        txtDeliveryAddress.Text = General.ClearScriptTag(txtDeliveryAddress.Text);
        txtEmailAddress.Text = General.ClearScriptTag(txtEmailAddress.Text);
        txtEngineSize.Text = General.ClearScriptTag(txtEngineSize.Text);
        txtEngineNumber.Text = General.ClearScriptTag(txtEngineNumber.Text);

        txtName.Text = Server.HtmlEncode(txtName.Text);
        txtOwnerName.Text = Server.HtmlEncode(txtOwnerName.Text);
        txtDeliveryName.Text = Server.HtmlEncode(txtDeliveryName.Text);
        txtAddress.Text = Server.HtmlEncode(txtAddress.Text);
        txtChassisNo.Text = Server.HtmlEncode(txtChassisNo.Text);
        txtDeliveryAddress.Text = Server.HtmlEncode(txtDeliveryAddress.Text);
        txtEmailAddress.Text = Server.HtmlEncode(txtEmailAddress.Text);
        txtEngineSize.Text = Server.HtmlEncode(txtEngineSize.Text);
        txtEngineNumber.Text = Server.HtmlEncode(txtEngineNumber.Text);
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        if (rfvManufactYear.Enabled && rfvManufactYear.ValidationGroup == strValidationGroup)
        {
            rfvManufactYear.Validate();
            if (rfvManufactYear.IsValid == false)
            {
                ddlManufactYear.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlManufactYear.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlManufactYear.ControlStyle.CssClass = "";
        }

        if (rfvCarMake.Enabled && rfvCarMake.ValidationGroup == strValidationGroup)
        {
            rfvCarMake.Validate();
            if (rfvCarMake.IsValid == false)
            {
                ddlCarMake.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlCarMake.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlCarMake.ControlStyle.CssClass = "";
        }

        if (rfvModelBodyCCDoor.Enabled && rfvModelBodyCCDoor.ValidationGroup == strValidationGroup)
        {
            rfvModelBodyCCDoor.Validate();
            if (rfvModelBodyCCDoor.IsValid == false)
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlModelBodyCCDoor.ControlStyle.CssClass = "";
        }

        if (rfvChassisNo.Enabled && rfvChassisNo.ValidationGroup == strValidationGroup)
        {
            rfvChassisNo.Validate();
            if (rfvChassisNo.IsValid == false)
            {
                txtChassisNo.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtChassisNo.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtChassisNo.ControlStyle.CssClass = "";
        }

        if (rfvName.Enabled && rfvName.ValidationGroup == strValidationGroup)
        {
            rfvName.Validate();
            if (rfvName.IsValid == false)
            {
                txtName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "";
        }

        if (rfvPlateNumber.Enabled && rfvPlateNumber.ValidationGroup == strValidationGroup)
        {
            rfvPlateNumber.Validate();
            if (rfvPlateNumber.IsValid == false)
            {
                txtPlateNumber.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtPlateNumber.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtPlateNumber.ControlStyle.CssClass = "";
        }

        if (rfvAddress.Enabled && rfvAddress.ValidationGroup == strValidationGroup)
        {
            rfvAddress.Validate();
            if (rfvAddress.IsValid == false)
            {
                txtAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtAddress.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtAddress.ControlStyle.CssClass = "";
        }

        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmailAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtEmailAddress.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtEmailAddress.ControlStyle.CssClass = "";
        }

        if (rfvDeliveryName.Enabled && rfvDeliveryName.ValidationGroup == strValidationGroup)
        {
            rfvDeliveryName.Validate();
            if (rfvDeliveryName.IsValid == false)
            {
                txtDeliveryName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtDeliveryName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtDeliveryName.ControlStyle.CssClass = "";
        }

        if (rfvDeliveryAddress.Enabled && rfvDeliveryAddress.ValidationGroup == strValidationGroup)
        {
            rfvDeliveryAddress.Validate();
            if (rfvDeliveryAddress.IsValid == false)
            {
                txtDeliveryAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtDeliveryAddress.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtDeliveryAddress.ControlStyle.CssClass = "";
        }

    }

    private bool Save()
    {
        Int64 _carresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        Int64 _refceuserid = 0;

        if (Session[General.CMICarId] != null)
        {
            _car = _cardb.GetCar(Convert.ToInt64(Session[General.CMICarId].ToString()), 0);
            if (Session[General.AgentId] != null)
            {
                _car.Info5 = "UPDATE";
            }
        }
        else
        {
            if (Session[General.AgentId] != null)
            {
                _car.Info4 = "NEW";
            }
        }

        if (_car == null)
        {
            _car = new CarDetailTH();
        }

        if (Session[CE.Global.General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[CE.Global.General.UserId]);
            _profile = _profiledb.GetProfile(_refceuserid);
            _contact = _contactdb.GetContact(_refceuserid);
            if (_profile != null && _contact != null)
            {
                _car.Info5 = _contact.Email;
                _car.Info6 = _contact.Mobile;
                _car.Info7 = _profile.SurName;
                if (_profile.FirstName.Trim().Length > 0)
                {
                    _car.Info8 = _profile.FirstName;//txtFirstName.Text.Trim();
                }
                _car.Info9 = (_profile.Gender.ToString().Trim() != "" ? _profile.Gender.ToString() : "M"); //ddlGender.GetGender();
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _car.Info10 = dteDOB.ToString("dd-MMM-yyyy");
                }
                else
                {
                    _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy"); //usrDOB.GetDate().ToString("dd-MMM-yyyy");
                }
                _car.Info11 = _profile.Occupation.ToString();// ddlOccupation.GetOccupation();
                _car.Info12 = _profile.JobNature;//ddlJobNature.GetJobNature();
                _car.Info13 = _profile.MaritalStatus.ToString();//ddlMaritalStatus.GetMaritalStatus();
                _car.Info14 = "0"; //ddlYearDriveSg.Text;
                _car.Info15 = _profile.Salutation;//ddlSalutation.GetSalutation();
                _profile = null;
                _contact = null;
            }
        }

        _car.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);

        if (Session[General.AgentId] != null)
        {
            _car.Info2 = Session[General.AgentId].ToString();
            _car.Info3 = DateTime.Now.ToString();
        }

        _car.CarMakeName = ddlCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);
        string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        _car.Info2 = lblCarVehicleType.Text;
        //LC = 210 or 220
        //PS = 110 or 120
        //PU = 320
        //SV = 110 or 120
        if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
        {
            _car.Info3 = "110";
        }
        else if (lblCarVehicleType.Text == "LC")
        {
            _car.Info3 = "210";
        }
        else if (lblCarVehicleType.Text == "PU")
        {
            if (_car.Door == 4)
            {
                _car.Info3 = "110";
            }
            else
            {
                _car.Info3 = "320";
            }
        }
        //_car.Info3 = ddlVehicleType.Text;
        _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
        _car.Status = true;
        _car.RefCEUserId = _refceuserid;
        //_car.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
        _car.CurrentStep = 1;
        _car.TotalStep = 4;

        // 03/2013
        //if (ddlInsurance.Text != "-1")
        //{
        //    _car.Info1 = ddlInsurance.Text;
        //}
        //else
        //{
         _car.Info1 = "150"; // = อื่นๆ  //ddlCurInsuranceCompany.Text; //Current Insurer ID
        //}
        _car.Info19 = "CM";
        _carresult = _cardb.Insert(_car);

        _car = null;
        _cardb = null;
        //_profile = null;
        //_profiledb = null;

        if (_carresult > 0)
        {
            Session[CE.Global.General.CMICarId] = _carresult.ToString();
        }
        else
        {
            lblMessage.Text = "Insert error!";
        }
        ////return _result > 0;
        //if (_carresult > 0)
        //{
        //    //CAR POLICY DETAILS
        //    CarPolicy _carpolicy = new CarPolicy();
        //    CarPolicyDB _carpolicydb = new CarPolicyDB();
        //    Int64 _carId = Convert.ToInt64(Session[General.CMICarId].ToString());
        //    Int64 _carpolicyid = 0;

        //    _carpolicy = _carpolicydb.GetCarPolicy(_carId, _refceuserid);
        //    if (_carpolicy != null)
        //    {
        //        _carpolicyid = _carpolicy.CECarPolicyId;
        //    }
        //    else
        //    {
        //        _carpolicy = new CarPolicy();
        //    }

        //    lblMessage.Text = "";
        //    if (Session[General.AgentId] != null)
        //    {
        //        _carpolicy.Info2 = Session[General.AgentId].ToString();
        //        _carpolicy.Info3 = DateTime.Now.ToString();
        //    }
        //    _carpolicy.CECarId = _carId;
        //    // 03/2013
        //    _carpolicy.InsuranceType = 10; //Convert.ToInt32(ddlInsuranceType.Text);
        //    _carpolicy.GarageType = Convert.ToInt32("1");
        //    _carpolicy.VehicleType = Convert.ToInt32("110");
        //    _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text);
        //    _carpolicy.ProvinceRegistration = "BKK"; //ddlProvinceRegistration.Text;
        //    _carpolicy.UseOfVehicle = "N/A";//ddlUseOfVehicle.Text;

        //    if (ddlExpiryMonth.Text != "-1")
        //    {
        //        int _iMonth = Convert.ToInt32(ddlExpiryMonth.Text);
        //        _carpolicy.CoverageCommenceDate = new DateTime(DateTime.Now.Year, _iMonth, 1); 
        //    }
        //    else
        //    {
        //        string strDate = ddlCTPLStartDay.Text;
        //        int _iDay = Convert.ToInt32(strDate.Substring(0, 2));
        //        strDate = ddlCTPLStartMonth.Text;
        //        int _iMonth = Convert.ToInt32(strDate.Substring(0, 2));
        //        int _iYear = Convert.ToInt32(strDate.Substring(2, 4));
        //        _carpolicy.CoverageCommenceDate = new DateTime(_iYear, _iMonth, _iDay); //DateTime.Today.AddDays(14);
        //    }
        //    _carpolicy.IsRedPlate = false; //rdoYesRedPlate.Checked;

        //    _carpolicy.IsAddAccMod = false;
        //    _carpolicy.AddAccModAmount = 0;
        //    _carpolicy.NCDPercent = Convert.ToInt32("20");
        //    _carpolicy.IsClaimLastYear = false;
        //    _carpolicy.IsCTPL = false;

        //    _carpolicy.IsAddDriver = false;
        //    _carpolicy.NoOfDriver = 0;
        //    //_carpolicy.Deductible = 0;
        //    _carpolicy.Deductible = Convert.ToInt16("-1");
        //    if (ddlInsurance.Text != "-1")
        //    {
        //        _carpolicy.CurrentInsurer = ddlInsurance.SelectedItem.Text;
        //    }
        //    else
        //    {
        //        _carpolicy.CurrentInsurer = Resources.CarInsurance.Others; //ddlCurInsuranceCompany.SelectedItem.Text;
        //    }
        //    _carpolicy.RefCEUserId = _refceuserid;
        //    //_carpolicy.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
        //    _carpolicy.Status = true;
        //    _carpolicy.CurrentStep = 2;
        //    _policyresult = _carpolicydb.Insert(_carpolicy);
        //    if (_policyresult > 0)
        //    {
        //        lblMessage.Text += "<br>Car policy saved successfully!";
        //        lblMessage.ForeColor = System.Drawing.Color.Blue;
        //    }
        //    else
        //    {
        //        lblMessage.Text = "Car policy did not save successfully!";
        //        lblMessage.ForeColor = System.Drawing.Color.Red;
        //        return false;
        //    }

        //    CarDriver _cardriver = new CarDriver();
        //    CarDriverDB _cardriverdb = new CarDriverDB();

        //    _cardriverdb.UpdateAllStatus(_carId, _refceuserid);

        //    _carpolicy = null;
        //    _carpolicydb = null;
        //}

        return _carresult > 0;
    }

    #endregion

    #region Email

    private string EmailAddress
    {
        get { return txtEmailAddress.Text.Trim(); }
    }

    //private bool SendCMIToUser()
    //{
    //    bool _retVal = false;
    //    string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive");

    //    string _emailTo = EmailAddress;
    //    string _emailSubject = "";
    //    if (Session["CMISERVICE"].ToString() == "1")
    //    {
    //        _emailSubject = "<Online> - " + Resources.EmailMessage.CMISubject1;
    //    }
    //    else if (Session["CMISERVICE"].ToString() == "2")
    //    {
    //        _emailSubject = "<Online> - " + Resources.EmailMessage.CMISubject2;
    //    }
    //    else if (Session["CMISERVICE"].ToString() == "3")
    //    {
    //        _emailSubject = "<Online> - " + Resources.EmailMessage.CMISubject3;
    //    }

    //    string _mailBody = "";
    //    string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
    //    string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");

    //    _mailBody = "<body class='email_body'>";
    //    _mailBody += "<style type='text/css'>";
    //    _mailBody += ".email_body {background: white;margin: 0;padding: 0;color: #4c4c4c;font-family: Arial, Helvetica, sans-serif;font-size: 0.85em;}";
    //    _mailBody += "a {text-decoration:underline;color:#2c95cc;} ";
    //    _mailBody += "#email_container {margin:0 auto;padding:20px;width:600px; height:auto;} ";
    //    _mailBody += "#email_body {width:100%; text-align: left !important;} ";
    //    _mailBody += ".email_pad10px {padding:10px;} ";
    //    _mailBody += ".email_results td {width:33%;} ";
    //    _mailBody += "</style>";
    //    _mailBody += "<center> <br /><br />";

    //    _mailBody += "<table cellpadding='0' cellspacing='0' border='0' width='570'>";
    //    _mailBody += "<tr><td width='570'><table cellspacing='0' cellpadding='0' width='100%' border='0'>";
    //    _mailBody += "<tr><td width='50%' valign='top'><strong>" + Session["CMITITLE"].ToString() + "</strong><br /><br />";
    //    _mailBody += Resources.Proposal.ThankYou + "<br/><br/>";
    //    _mailBody += "<br/></td><td width='50%' align='right' valign='top'><img src='" + _currentDomainUrl + "/images/public/logo/logo_gluaygluay.png' width='130' height='99'/></td></tr>";
    //    _mailBody += "</table>";

    //    _mailBody += "<table cellspacing='0' cellpadding='2' width='570' border='0'>";
    //    _mailBody += "<tr><td width='25%' valign='top'><strong>" + Resources.ResultPage.CTPL + "</strong></td>";
    //    _mailBody += "<td width='25%' valign='top'><strong>" + Resources.CarInsurance.TaxAndPanalty + "</strong></td>";
    //    _mailBody += "<td width='25%' valign='top'><strong>" + Resources.CarInsurance.Charged + "</strong></td>";
    //    _mailBody += "<td width='25%' valign='top'><strong>" + Resources.CarInsurance.Total + "</strong></td></tr>";

    //    _mailBody += "<tr><td valign='top'>" + lblSumCTPL.Text + "</td>";
    //    _mailBody += "<td valign='top'>" + lblSumTaxAndPanalty.Text + "</td>";
    //    _mailBody += "<td valign='top'>" + lblSumCharged.Text + "</td>";
    //    _mailBody += "<td valign='top'>" + lblTotal.Text + "</td></tr>";
    //    _mailBody += "</table> <br /><br />";

    //    _mailBody += "<table cellpadding='5' cellspacing='0' border='0' width='100%' class='table_details'>";

    //    //_mailBody += "<table cellspacing='0' cellpadding='2' width='570' border='0'>";
    //    //_mailBody += " <tr><td width='50%' valign='top'>" + Resources.Proposal.InsuranceType + " " + _InsuranceType + "</td><td width='50%;' valign='top'>&nbsp;</td>";
    //    //_mailBody += "</tr><tr><td valign='top'>" + Resources.Proposal.RefNo + ": " + _refNo + "</td><td valign='top'>" + Resources.Proposal.OrderDate + ": " + DateTime.Now.ToString("dd/MMM/yyyy") + "</td></tr>";
    //    //_mailBody += "<tr><td valign='top'>" + Resources.Proposal.NameLastname + ": " + _Name + "</td><td valign='top'>" + Resources.Proposal.LicensePlateNo + ": " + _CarPlate + "</td></tr>";
    //    //_mailBody += "<tr><td valign='top'>" + Resources.Proposal.MakeModel + ": " + _CarMakeModel + "</td><td valign='top'>" + Resources.Proposal.CarYear + ": " + _CarYear + "</td></tr>";
    //    //_mailBody += "<tr><td valign='top'>" + Resources.Proposal.GarageType + ": " + _GarageType + "</td><td valign='top'>" + Resources.Proposal.NamedDrivers + ": " + _NameDriver + "</td></tr>";
    //    //_mailBody += "<tr><td valign='top'>" + Resources.Proposal.PolicyStartDate + ": " + _PolicyStartDate + " </td><td valign='top'>" + Resources.Proposal.NCB + ": " + _NCB + "</td></tr>";
    //    //_mailBody += "</table> <br /><br />";

    //    //_mailBody += "<tr>";
    //    //_mailBody += "<td width='45%'></td>";
    //    //_mailBody += "<td width='55%' align='center' style='background:#e0e0e0; border-bottom:white 1px dashed;'><img src='" + _currentDomainUrl + logourl + "' width='130' style='padding:3px;'/></td>";
    //    //_mailBody += "</tr>";
    //    //_mailBody += "<tr>";
    //    //_mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.Insurer + "</strong></td>";
    //    //_mailBody += "<td align='center' style='background:#d5d5d5; color:white;'><strong>" + insurername + "</strong></td>";
    //    //_mailBody += "</tr>";

    //    //divCarDetail
    //    if (Session["CMISERVICE"].ToString() != "3")
    //    {
    //        _mailBody += "<tr>";
    //        _mailBody += "<td></td>";
    //        _mailBody += "<td align='center' style='background:#c5c5c5'><strong>" + Resources.CarInsurance.CarAndInsuranceDetail + "</strong></td>";
    //        _mailBody += "</tr>";

    //        _mailBody += "<tr>";
    //        _mailBody += "<td><strong>" + Resources.CarInsurance.CarModelYear + "</strong></td>";
    //        _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + ddlManufactYear.SelectedItem.Text + "</td>";
    //        _mailBody += "</tr>";

    //        _mailBody += "<tr>";
    //        _mailBody += "<td><strong>" + Resources.CarInsurance.CarMakeModel + "</strong></td>";
    //        _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + ddlCarMake.SelectedItem.Text + " - " + ddlModelBodyCCDoor.SelectedItem.Text + "</td>";
    //        _mailBody += "</tr>";

    //        _mailBody += "<tr>";
    //        _mailBody += "<td><strong>" + Resources.CarInsurance.ChassisNo + "</strong></td>";
    //        _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtChassisNo.Text + "</td>";
    //        _mailBody += "</tr>";

    //        _mailBody += "<tr>";
    //        _mailBody += "<td><strong>" + Resources.CarInsurance.EngineNumber + "</strong></td>";
    //        _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtEngineNumber.Text + "</td>";
    //        _mailBody += "</tr>";

    //        _mailBody += "<tr>";
    //        _mailBody += "<td><strong>" + Resources.CarInsurance.EngineSize + "</strong></td>";
    //        _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtEngineSize.Text + "</td>";
    //        _mailBody += "</tr>";

    //        _mailBody += "<tr>";
    //        _mailBody += "<td><strong>" + Resources.CarInsurance.CTPLStartDate + "</strong></td>";
    //        _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtCTPLDate.Text + "</td>";
    //        _mailBody += "</tr>";
    //    }

    //    //divCarTaxDetail
    //    if (Session["CMISERVICE"].ToString() != "1")
    //    {
    //        _mailBody += "<tr>";
    //        _mailBody += "<td></td>";
    //        _mailBody += "<td align='center' style='background:#c5c5c5'><strong>" + Resources.CarInsurance.TaxRenewalDetail + "</strong></td>";
    //        _mailBody += "</tr>";

    //        _mailBody += "<tr>";
    //        _mailBody += "<td><strong>" + Resources.CarInsurance.RegistrationDate + "</strong></td>";
    //        _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtRegistrationDate.Text + "</td>";
    //        _mailBody += "</tr>";
    //    }

    //    _mailBody += "<tr>";
    //    _mailBody += "<td></td>";
    //    _mailBody += "<td align='center' style='background:#c5c5c5'><strong>" + Resources.CarInsurance.AssuredData + "</strong></td>";
    //    _mailBody += "</tr>";

    //    _mailBody += "<tr>";
    //    _mailBody += "<td><strong>" + Resources.CarInsurance.Name + "</strong></td>";
    //    _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtName.Text + "</td>";
    //    _mailBody += "</tr>";

    //    _mailBody += "<tr>";
    //    _mailBody += "<td><strong>" + Resources.CarInsurance.OwnerName + "</strong></td>";
    //    _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtOwnerName.Text + "</td>";
    //    _mailBody += "</tr>";

    //    _mailBody += "<tr>";
    //    _mailBody += "<td><strong>" + Resources.ProposalForm.CarPlate + "</strong></td>";
    //    _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtPlateNumber.Text + " " + ddlProvince.SelectedItem.Text + "</td>";
    //    _mailBody += "</tr>";

    //    //if (chkRedPlate.Checked)
    //    //{
    //    //    _mailBody += "<tr>";
    //    //    _mailBody += "<td><strong>" + Resources.CarInsurance.RedPlate + "</strong></td>";
    //    //    _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + Resources.CarInsurance.Option_Yes + "</td>";
    //    //    _mailBody += "</tr>";
    //    //}

    //    _mailBody += "<tr>";
    //    _mailBody += "<td><strong>" + Resources.CarInsurance.AssuredAddress + "</strong></td>";
    //    _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtAddress.Text + "</td>";
    //    _mailBody += "</tr>";

    //    _mailBody += "<tr>";
    //    _mailBody += "<td></td>";
    //    _mailBody += "<td align='center' style='background:#c5c5c5'><strong>" + Resources.CarInsurance.DeliveryInfo + "</strong></td>";
    //    _mailBody += "</tr>";

    //    _mailBody += "<tr>";
    //    _mailBody += "<td><strong>" + Resources.CarInsurance.Name + "</strong></td>";
    //    _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtDeliveryName.Text + "</td>";
    //    _mailBody += "</tr>";

    //    _mailBody += "<tr>";
    //    _mailBody += "<td><strong>" + Resources.CarInsurance.DeliveryAddress + "</strong></td>";
    //    _mailBody += "<td align='center' style='background:#d5d5d5;border-bottom:1px solid #ccc;' >" + txtDeliveryAddress.Text + "</td>";
    //    _mailBody += "</tr>";

    //    _mailBody += "</table>";

    //    _mailBody += "<br/>";
    //    _mailBody += "<br/>";

    //    //_mailBody += "<u>" + Resources.Proposal.ForBankIn + "</u>";
    //    //_mailBody += "<br/>" + Resources.Proposal.ForBankInMsg1;
    //    //_mailBody += "<br/>";
    //    //_mailBody += "<br/>" + Resources.Proposal.ForBankInMsg2;
    //    //_mailBody += "<br/>";
    //    //_mailBody += "<br/><strong>" + Resources.Proposal.Remarks + "</strong>";
    //    //_mailBody += "<br/>" + Resources.Proposal.RemarksMsg1;
    //    //_mailBody += "<br/>";
    //    _mailBody += "<br/><strong>" + Resources.Proposal.CompareXpress + "</strong>";
    //    _mailBody += "<br/>" + Resources.Proposal.CompareXpressAddress;

    //    _mailBody += "</td></tr>";
    //    _mailBody += "<tr><td id='email_footer'>";
    //    _mailBody += "</td></tr></table>";

    //    _mailBody += "<hr />";
    //    _mailBody += Resources.EmailMessage.Footer;
    //    _mailBody += "<br/>";
    //    _mailBody += "<br /><i>" + Resources.EmailMessage.NoReply + "</i>";
    //    _mailBody += "<hr />";
    //    _mailBody += "</center></body>";

    //    if (MyMailManager.SendSelectedCARMessage(_emailTo, _emailSubject, _mailBody))
    //    {
    //        _retVal = true;
    //    }
    //    else
    //    {
    //        _retVal = false;
    //    }

    //    return _retVal;
    //}

    #endregion

    #region login existing user

    protected void lbnLoginPopup_Click(object sender, EventArgs e)
    {
        Response.Redirect(CE.Global.General.GetUrl("~/car-insurance/sign-in.aspx", Page));
    }

    protected void imgbtnLogin_Click(object sender, EventArgs e)
    {
        if (AutoLogin(100))
        {
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());

            }

            Int64 _carId = 0;

            if (Session[General.CMICarId] != null)
            {
                _carId = Convert.ToInt64(Session[General.CMICarId].ToString());
            }
            else
            {
                //Response.Redirect("carandpolicy_details.aspx");

                //_redirectUrl = CE.Global.General.GetUrl("~/car-insurance/car-details.aspx", Page);
                //Response.Redirect(_redirectUrl);
            }

            if (_userId > 0)
            {
                inputLoginHide.Value = "1";

                //update RefIds
                CarDetailTHDB cardb = new CarDetailTHDB();
                cardb.UpdateCarDetailPolicy(_carId, _userId);

                //btnNext.Enabled = true;
                //divPassword.Visible = false;
                //vsCarProfile.Visible = false;
                //divNewErrorMessage.Visible = false;

                vsCarProfile.Enabled = false;
                mpePassword.Hide();
                //divExisting.Visible = false;
                //ShowCustomerDetail(_userId);

                inputLoginCount.Value = "0";

                //this.Page_Load(this, null);
                //Response.Redirect("profile.aspx");

                //if (rdoExistingYes.Checked)
                //{
                   Response.Redirect(CE.Global.General.GetUrl("~/cmi/cmi-detail.aspx", Page));
                //}
                //else
                //{
                //    btnNext_Click(sender, e);
                //}

                txtName.Text = "sssssss";
            }

        }
        else
        {

            Int32 logincount = Convert.ToInt32(inputLoginCount.Value.Trim());
            inputLoginCount.Value = (logincount + 1).ToString();

            if (logincount == 2)
            {
                inputHideSignal.Value = "1";
            }
            else if (logincount >= 3)
            {
                this.btnPasswordClose_Click(this, null);
            }
            else
            {
                vsCarProfile.Enabled = false;
                mpePassword.Show();
            }
        }
    }

    protected void btnPasswordClose_Click(object sender, EventArgs e)
    {
        inputLoginCount.Value = "0";

        //_redirectUrl = CE.Global.General.GetUrl("~/car-insurance/car-details.aspx", Page);
        //Response.Redirect(_redirectUrl);
    }

    private bool AutoLogin(int LoginType)
    {
        bool isLoggedin = false;
        AccountStatus _accountstatus = new AccountStatus();
        AccountStatusDB _accountstatusdb = new AccountStatusDB();
        AccountDB _accountdb = new AccountDB();
        //Check Customer Account

        Account _account = _accountdb.GetUserAccount(txtExEmail.Text.ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));

        if (_account != null)
        {
            if (CheckUserLoginCached(_account.CEID.ToString()))
            {
                _accountstatus = _accountstatusdb.GetAccountStatus(_account.CEID, 400);

                if (Server.HtmlDecode(txtExAuthCode.Text) == _account.AuthCode)
                {
                    if (_account.Status == true)
                    {
                        isLoggedin = true;

                        if (_account.Info1 == "0")
                        {
                            //Reset Email Fail Message
                            _account.Info1 = "";
                            _account.Info2 = "";
                            _accountdb.Insert(_account);
                        }

                        _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                        lblEmailMessage.Visible = false;
                        GetUserInformation(_account);
                        //SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                        CE.Global.General.CreateUpdateUserLoginCached(Page);
                        _account = null;
                        //if (LoginType == 100)
                        //{
                        //    //Response.Redirect("profile.aspx");
                        //    Response.Redirect("carAndpolicy_details.aspx");
                        //}
                        //else
                        //{
                        //    if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
                        //        Response.Redirect("~/User/ViewResultHistory.aspx?resulttitle=100");
                        //    else
                        //    {
                        //        Response.Redirect("~/User/EditProfile.aspx");
                        //    }
                        //}
                    }
                    else
                    {
                        lblEmailMessage.Visible = true;
                        lblEmailMessage.Text = "Your email has been blocked!";
                    }
                }
                else
                {
                    _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 0);
                    lblEmailMessage.Visible = true;
                    lblEmailMessage.Text = Resources.Menu.EmailPasswordIncorrect;//"Email address or password is incorrect.";
                }
            }
            else
            {
                string _redirectUrl = "";
                //Response.Redirect("UserMessage.aspx?ErrorCode=1993");
                //Response.Redirect("~/user/usermessage.aspx?mt=UM&ec=1993");
                _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                Session["UMMSG"] = "UM,1993";
                Response.Redirect(_redirectUrl);
            }
        }
        else
        {
            lblEmailMessage.Visible = true;
            lblEmailMessage.Text = Resources.Menu.EmailPasswordIncorrect;
        }

        return isLoggedin;
    }

    private void GetUserInformation(Account _account)
    {
        DateTime dtNow = new DateTime();
        dtNow = DateTime.Now;
        Session[CE.Global.General.UserId] = _account.CEID;
        Session[CE.Global.General.UserTypeId] = _account.UserTypeId;

        if (_account.UserTypeId == Convert.ToInt32(CE.Global.CEUserType.Provider))
        {
            CE.Provider.ProviderCompanyLink _comlink = new CE.Provider.ProviderCompanyLink();
            CE.Provider.ProviderCompanyLinkDB _comlinkdb = new CE.Provider.ProviderCompanyLinkDB();
            _comlink = _comlinkdb.GetProviderCompanyId(_account.CEID);
            if (_comlink != null)
            {
                Session[CE.Global.General.ProviderCompanyId] = _comlink.ProviderCompanyId;
            }
        }

        Session[CE.Global.General.UserEmail] = _account.Email;
        Session[CE.Global.General.StartTime] = dtNow.ToString();
        bool isProfileComplete = false;
        bool isContactComplete = false;

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _contact = _contactdb.GetContact(_account.CEID);

        _profile = _profiledb.GetProfile(_account.CEID);

        if (_contact != null)
        {
            isContactComplete = true;
            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        }
        else
        {
            Session[CE.Global.General.UserPhoneNo] = null;
        }

        if (_profile != null)
        {
            if (_profile.FirstName != null && _profile.FirstName != string.Empty)
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName) + " " + Server.HtmlDecode(_profile.FirstName);
            }
            else
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
            }

            if (!string.IsNullOrEmpty(_profile.IDType) &&
                !string.IsNullOrEmpty(_profile.IDNo) &&
                _profile.IDNo.Length == 9)
            {
                Session[CE.Global.General.UserICNumber] = _profile.IDType + " " + _profile.IDNo;
            }

            if (_profile.Status.ToLower() == "complete")
            {
                isProfileComplete = true;
            }
            else
            {
                isProfileComplete = false;
            }
        }
        else
        {
            Session[CE.Global.General.UserName] = null;
        }

        if (isProfileComplete && isContactComplete)
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
        }
        else
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "0";
        }

    }

    private bool CheckUserLoginCached(string UserId)
    {
        bool _retValue = false;
        string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.UserCacheName");
        sKey += UserId;
        if (HttpContext.Current.Cache[sKey] == null)
        {
            _retValue = true;
        }
        else
        {
            if (Session[General.UserId] == null)
            {
                this.Cache.Remove(sKey);
                _retValue = true;
            }
            else
            {
                _retValue = false;
            }
        }
        return _retValue;
    }

    #endregion

    protected void chkTax_CheckedChanged(object sender, EventArgs e)
    {
        rfvRegDay.Enabled = chkTax.Checked;
        rfvRegMonth.Enabled = chkTax.Checked;
        rfvRegYear.Enabled = chkTax.Checked;
        if (chkTax.Checked)
        {
            //divCarTaxDetail.Style.Add("display", "");
            if (hidCarType.Value == "1")
            {
                rfvEngineSize.Enabled = true;
            }
            else
            {
                rfvCarWeight.Enabled = true;
            }
        }
        else
        {
            //divCarTaxDetail.Style.Add("display", "none");
            lblSumTaxAndPanalty.Text = "";
            hidCalTaxAndPanalty.Value = "";
            lblSumCharged.Text = "";
            hidSumCharged.Value = "";
            if (Session["CMITOTAL"] != null)
            {
                lblTotal.Text = Session["CMITOTAL"].ToString();
                hidTotal.Value = Session["CMITOTAL"].ToString();
            }
            if (hidCarType.Value == "1")
            {
                rfvEngineSize.Enabled = false;
            }
            else
            {
                rfvCarWeight.Enabled = false;
            }
        }
    }

    protected void chkCopyAddress_CheckedChanged(object sender, EventArgs e)
    {
        if (chkCopyAddress.Checked)
        {
            rfvDeliveryName.Enabled = false;
            revDeliveryName.Enabled = false;
            rfvDeliveryAddress.Enabled = false;
        }
        else
        {
            rfvDeliveryName.Enabled = true;
            revDeliveryName.Enabled = true;
            rfvDeliveryAddress.Enabled = true;
        }
    }
}
